﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.NodeFactory;
using Vega.USiteBuilder;
using umbraco.cms.businesslogic.web;
using SPCFMedicineInformer.Constants;
using umbraco.BusinessLogic;
using System.Web.Configuration;
using SPCFMedicineInformer.Helpers;
using System.Text;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_Slideshow_Item : System.Web.UI.MasterPage
    {
        int id = 0;
        protected void Page_Init(object sender, EventArgs e)
        {
            ((umbraco.UmbracoDefault)this.Page).ValidateRequest = false;

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNewSlide = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                if (id > 0)
                {
                    var node = new Node(id);
                    var slideItem = node != null && node.NodeTypeAlias == "SlideshowItem" ? ContentHelper.GetByNodeId<DocumentTypes.SlideshowItem>(id) : null;
                    if (slideItem != null)
                    {
                        slideImage.ImageUrl = slideItem.ImageUrl;
                        ShowExistingImage(!string.IsNullOrEmpty(slideItem.ImageUrl) ? true : false);
                        txtTitle.Text = slideItem.SlideTitle;
                        taContent.Value = slideItem.Content;
                        txtReadMoreLink.Text = slideItem.ReadMoreLink;
                        cbShowInFrontpage.Checked = slideItem.ShowInFrontpage;
                        if (isNewSlide)
                            FormHelper.ShowMessage(MessageType.Done, "Slideshow Succesfully Saved!", MsgLiteral);
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);

                    }
                }
                else
                {
                    ShowExistingImage(false);
                    btnAddNewSlide.Visible = false;
                }
            }
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void ShowExistingImage(bool value,bool cancel = false)
        {
            plcExistingImage.Visible = value;
            lbCancelUpload.Visible = cancel;
            plcNewImage.Visible = !value;
        }
        string UploadImage(int id)
        {
            if (FileUpload1.HasFile)
            {
                string strFile = WebConfigurationManager.AppSettings["ImagePath"] + id.ToString() + "-" +FileUpload1.FileName;
                string filepath = Server.MapPath(strFile);
                FileUpload1.SaveAs(filepath);
                ShowExistingImage(true);
                slideImage.ImageUrl = strFile;
                return strFile.Remove(0,1);
            }
            return "";
        }
        void TransferDetailsToUmbraco(Document doc)
        {
            if (plcNewImage.Visible)
            {
                doc.getProperty(UmbracoPropertyName.IMAGE_URL).Value = UploadImage(doc.Id);
            }
            
            doc.getProperty(UmbracoPropertyName.SLIDE_TITLE).Value = txtTitle.Text;
            doc.getProperty(UmbracoPropertyName.CONTENT).Value = taContent.Value;
            doc.getProperty(UmbracoPropertyName.SHOW_IN_FRONTPAGE).Value = cbShowInFrontpage.Checked;
            doc.getProperty(UmbracoPropertyName.READ_MORE_LINK).Value = txtReadMoreLink.Text;
            doc.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(doc.Id);
        }
        void UpdateSlide()
        {
            if (id > 0)
            {
                var doc = new Document(id);
                if (doc != null)
                {
                    TransferDetailsToUmbraco(doc);
                }
            }
            
        }
        int AddSlide()
        {
            DocumentType docType = DocumentType.GetByAlias("SlideshowItem");
            Node SlideshowFolder = Helpers.UmbracoNodeHelper.GetSlideshowFolder();
            if (SlideshowFolder != null)
            {
                Document newDoc = Document.MakeNew(txtTitle.Text,docType,User.GetUser(0),SlideshowFolder.Id);
                TransferDetailsToUmbraco(newDoc);
                if (newDoc != null)
                    return newDoc.Id;
            }
            return 0;
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)//update medicine
                {
                    UpdateSlide();
                    FormHelper.ShowMessage(MessageType.Done, "Slideshow Succesfully Saved!", MsgLiteral);
                }
                else
                {
                    id = AddSlide();
                    Response.Redirect("/admin/utilities/slideshows/slideshow-entry?id=" + id + "&n=1");
                }
            }
            

        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/slideshows.aspx");
        }
        protected void btnAddNewSlide_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/slideshows/slideshow-entry");
        }
        bool IsValidate()
        {
            bool result = true;
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";

            if (string.IsNullOrEmpty(txtTitle.Text))
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Title is required!"));
                result = false;
            }
            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        protected void lbUploadNew_Click(object sender, EventArgs e)
        {
            ShowExistingImage(false,true);

        }
        protected void lbCanceUpload_Click(object sender, EventArgs e)
        {
            ShowExistingImage(true);

        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/slideshows.aspx");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
    }
}